package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IBlogService blogService;
    @Override
    public Result queryBlogById(Long id) {
        // 查询blog
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("笔记不存在！！");
        }

        // 2.查询blog有关的用户  即 发表这篇博客的用户的id和图标
        queryBlogUser(blog);

        // 3.查询blog是否被点赞
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        UserDTO userDTO = UserHolder.getUser();
        Long userDTOId = userDTO.getId();
        String key = BLOG_LIKED_KEY+ id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userDTOId.toString());

        if(score==null){
            // 没有点赞过
            boolean isSuccess = update().setSql("liked = liked +1").eq("id", id).update();
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userDTOId.toString(),System.currentTimeMillis());
            }
        }else{
            // 点赞过
            boolean isSuccess = update().setSql("liked = liked -1").eq("id", id).update();
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userDTOId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {

        String key = BLOG_LIKED_KEY + id;
        Set<String> top5Set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5Set == null || top5Set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> reidUserList = top5Set.stream().map(Long::valueOf).collect(Collectors.toList());
        String idList = StrUtil.join(",", reidUserList);
        List<User> userDTOS1 = userService.query()
                .in("id", idList).last("ORDER BY FIELD(id," + idList + ")").list();

        List<UserDTO> userDTOS = userService.query().
                in("id", reidUserList)
                .last("order by FIELD (id," + idList + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);

    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long userID = UserHolder.getUser().getId();
        String key= FEED_KEY+userID;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //对typeTuples进行非空判断
        if(typedTuples==null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 对typedTuples进行解析
        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0L;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple:typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            Long time = typedTuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                // 因为是逆序获得数据
                minTime = time;
                os = 1;
            }
        }

        os = minTime == max? os+offset : os;
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        String idstr = StrUtil.join(",",ids);
        List<Blog> blogs = blogService.query().in("id", ids).last("order by field ( id," + idstr + ")").list();
        for(Blog blog:blogs){
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        scrollResult.setList(blogs);

        return Result.ok(scrollResult);

    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    public void isBlogLiked(Blog blog){
        UserDTO userDTO = UserHolder.getUser();
        Long userId = userDTO.getId();
        String redisKey = BLOG_LIKED_KEY+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(redisKey, userId.toString());

        blog.setIsLike(score!=null);

    }
}
